/*
 * Class MixTexStuff
 * used for building/converting the tex files
 *
 */

package com.meraklisina.latexeditor;

import com.meraklisina.latexeditor.mdi.TextEditor.TextEditors;
import java.io.*;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
import javax.swing.JTabbedPane;
import javax.swing.JTextArea;

/**
 *
 * @author Suleyman Melikoglu
 */
public class MixTexStuff {

	public MixTexStuff(){

    }

    /**
     * convert the tex file to given format
     * this method is responsible for converting, vieweing and logging operations
     *
     * @param String program
     * @param JTextArea textAreaOutput for logging the messages
     * @param JTabbedPane tab_Editors
     * @return void
     */
    public void buildProcess(String program, JTextArea textAreaOutput, JTabbedPane tab_Editors ){
        try {

            TextEditors editors = new TextEditors();
            String filepath = editors.GetRealPath(tab_Editors.getSelectedIndex());
            String filename = editors.GetRealPathTitle(tab_Editors.getSelectedIndex());
            String os = BlueLatexEditor._operatingSystem;
            int operationStatus = -1;

            textAreaOutput.append("\n-----------\n");

            //get rid of the extension
            int whereDot = filename.lastIndexOf('.');
            if (0 < whereDot && whereDot <= filename.length() - 2 ) {
                filename = filename.substring(0, whereDot);
                //extension = filename.substring(whereDot+1);
            }

            String outputPath = filepath;
            //get rid of the filename and extension
            int whereFilename = outputPath.lastIndexOf("\\");
            if (0 < whereFilename && whereFilename <= outputPath.length() - 2 ) {
                outputPath = outputPath.substring(0, whereFilename);
            }
            else
            {
            	whereFilename = outputPath.lastIndexOf("/");
            	outputPath = outputPath.substring(0, whereFilename);
            }

            String cmd = null;
            Process p;
            
            if(os.contains("Windows"))
            {
            	String MixTexPath = BlueLatexEditor._miktexPath;
            	if(program.equalsIgnoreCase("dvips.exe")){
                    //convert to dvi first

            		String[] exDVI = {MixTexPath+ "latex.exe", "-halt-on-error", "-interaction", "nonstopmode", "-output-directory", outputPath, filepath};
            		ProcessBuilder pbDVI = new ProcessBuilder();
            		pbDVI.command(exDVI);
                	p = pbDVI.start();
                	// then convert the dvi to ps file                	
                	Process pPS;
                	String[] exPS = {MixTexPath + program,  "-f", outputPath + "\\" + filename + ".dvi", "-o", outputPath + "\\" + filename+".ps", "-quiet"};
                   	ProcessBuilder pbPS = new ProcessBuilder();
                	pbPS.command(exPS);
                	pPS = pbPS.start();
                	
                	operationStatus = this._buildHelper(pPS, textAreaOutput);
            		
                }else{
                	String[] exPDF = {MixTexPath + program, "-halt-on-error", "-interaction", "nonstopmode", "-output-directory", outputPath, filepath};
                	ProcessBuilder pbPDF = new ProcessBuilder();
                	pbPDF.command(exPDF);
                	p = pbPDF.start();
                	
                    operationStatus = this._buildHelper(p,textAreaOutput);
                }
            }
            else if(os.contains("Linux"))
            {
            	if(program.equalsIgnoreCase("dvips"))
            	{
            		String cmdTemp = "latex " + " -output-directory=" + outputPath + " -halt-on-error " + "-interaction=nonstopmode " +
            						"-job-name=" + filename + " -quiet " + filepath;
            		this._buildHelper( Runtime.getRuntime().exec( cmdTemp ), textAreaOutput);

            		cmd = "dvips -f " +
                    outputPath + "/" + filename + ".dvi -o " +
                    outputPath + "/" + filename + ".ps -quiet";
            		
	                // then convert the dvi to ps file
	                //p = Runtime.getRuntime().exec( cmd );
            		operationStatus = this._buildHelper( Runtime.getRuntime().exec( cmd ), textAreaOutput);
            	}
            	else
            	{
            		// IT : No need to set program path in linux
                	cmd = program + " -output-directory=" + outputPath + " -interaction=nonstopmode" + " -job-name="
                		+ filename + " -quiet"  + " " + filepath;
                	operationStatus = this._buildHelper( Runtime.getRuntime().exec( cmd ), textAreaOutput);
            	}
            }
            
            //textAreaOutput.append("\nCommand: \n" + cmd);
            //textAreaOutput.append("\nAction Start \n");
            
            if(operationStatus == 0)
            {
	            // force to open the file
	            try{
	                // if the os is windows, then view the file with system's default
	                if(os.contains("Windows")){
	                    if(program.equalsIgnoreCase("latex.exe")){
	                        Runtime.getRuntime().exec("rundll32 url.dll,FileProtocolHandler " + outputPath + "\\" + filename + ".dvi");   //open the file chart.pdf
	                        //this._buildHelper(p);
	                        textAreaOutput.append("\nOutput file: " + outputPath + "\\" + filename + ".dvi");
	                    }else if(program.equalsIgnoreCase("pdflatex.exe")){
	                        Runtime.getRuntime().exec("rundll32 url.dll,FileProtocolHandler " + outputPath + "\\" + filename + ".pdf");   //open the file chart.pdf
	                        textAreaOutput.append("\nOutput file: " + outputPath + "\\" + filename + ".pdf");
	                    }else if(program.equalsIgnoreCase("dvips.exe")){
	                        Runtime.getRuntime().exec("rundll32 url.dll,FileProtocolHandler " + outputPath + "\\" + filename + ".ps");   //open the file chart.pdf
	                        textAreaOutput.append("\nOutput file: " + outputPath + "\\" + filename + ".ps");
	                    }
	                }else if(os.contains("Linux")){
	                	if(program.equalsIgnoreCase("pdflatex"))
	                	{
	                    	Runtime.getRuntime().exec("evince " + outputPath + "/" + filename + ".pdf");
	                    	textAreaOutput.append("\nOutput file: " + outputPath + "/" + filename + ".pdf");                		
	                	}else if(program.equalsIgnoreCase("latex")){
	                		Runtime.getRuntime().exec("evince " + outputPath + "/" + filename + ".dvi");
	                		textAreaOutput.append("\nOutput file: " + outputPath + "/" + filename + ".dvi");
	                	}else if(program.equalsIgnoreCase("dvips")){
	                		Runtime.getRuntime().exec("evince " + outputPath + "/" + filename + ".ps");
	                		textAreaOutput.append("\nOutput file: " + outputPath + "/" + filename + ".ps");
	                	}
	                }
	                else
	                {
	                	// inform the user that we cannot provide a viewer, go and get a windows machine buddy.
	                	textAreaOutput.setText("\nFiles are processed successfully, However we do not support your operation system for viewing those files.");
	                }
	                textAreaOutput.append("\nOperation successful!\n\n");
	            }catch (Exception e){
	                 //JOptionPane.showMessageDialog(null,"Cannot open the file!","Error",JOptionPane.ERROR_MESSAGE);
	                textAreaOutput.append("\nCannot open the file!");
	            }
            }else{
            	textAreaOutput.append("\n!!! Operation not successful. Please see log details !!!\n\n");
            }

        } catch (IOException ex) {
            //Logger.getLogger(OpenTexEditorView.class.getName()).log(Level.SEVERE, null, ex);
            //JOptionPane.showMessageDialog(null,"Cannot complete the request!","Error",JOptionPane.ERROR_MESSAGE);
            textAreaOutput.append("\nCannot complete the request \n");
        }
    }

    private int _buildHelper(Process p, JTextArea textAreaOutput){
        try {
            BufferedReader in = new BufferedReader(new InputStreamReader(p.getInputStream()));
            String line;
            long t1;
            while ((line = in.readLine()) != null) {
                t1 = System.currentTimeMillis();
                if (t1 > 1000000) {
                    //JOptionPane.showMessageDialog(null,"Cannot compile the file!","Compile error",JOptionPane.ERROR_MESSAGE);
                    //break;
                }
                textAreaOutput.append(line + "\n");
            }
        } catch (IOException ex) {
            Logger.getLogger(MixTexStuff.class.getName()).log(Level.SEVERE, null, ex);
        }
        
        // IT : Wait for application to be terminated
        try
        {
        	p.waitFor();
        } catch (InterruptedException e){
        	e.printStackTrace();
        }
        
        System.out.println("Exit : " + p.exitValue());
        return p.exitValue();
    }

    public static String getFileNameWithoutExtension(String fileName) {
        File tmpFile = new File(fileName);
        tmpFile.getName();
        int whereDot = tmpFile.getName().lastIndexOf('.');
        if (0 < whereDot && whereDot <= tmpFile.getName().length() - 2 ) {
            return tmpFile.getName().substring(0, whereDot);
            //extension = filename.substring(whereDot+1);
        }
        return "";
    }


}
